package com.gitee.huanminabc.dynamicdb.aop.dbswitch;

import com.gitee.huanminabc.dynamicdb.aop.DBSwitch;
import com.gitee.huanminabc.dynamicdb.common.DynamicDbException;
import com.gitee.huanminabc.dynamicdb.core.DBSwatch;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.ClassUtils;

import java.util.List;
/**
 * @author huanmin
 * @date 2024/11/22
 */
public class DBSwitchAdvice implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Class<?> aClass1 = invocation.getThis().getClass();
        //先找接口上的注解
        List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(aClass1);
        for (Class<?> aClass : allInterfaces) {
            DBSwitch annotation = aClass.getAnnotation(DBSwitch.class);
            if (annotation!=null){
                return DBSwatch.threadDb(annotation.value(), invocation::proceed);
            }
        }
        //再找类上的注解
        DBSwitch classs =aClass1.getAnnotation(DBSwitch.class);
        if (classs!=null){
            return DBSwatch.threadDb(classs.value(), invocation::proceed);
        }
        //再找方法上的注解
        DBSwitch method  = invocation.getMethod().getAnnotation(DBSwitch.class);
        if (method!=null){
            return DBSwatch.threadDb(method.value(), invocation::proceed);
        }
       throw new DynamicDbException(aClass1.getName()+"未找到DBSwitch注解");
    }
}
